<template>
  <el-card class="full-card">
    <h2 class="page-title">用户管理</h2>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" label-width="80px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="用户名">
            <el-input v-model.trim="queryParams.username" placeholder="请输入用户名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮箱">
            <el-input v-model.trim="queryParams.email" placeholder="请输入邮箱" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号">
            <el-input v-model.trim="queryParams.phoneNumber" placeholder="请输入手机号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="正常" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-button type="primary" @click="handleSearch" class="search-btn">查询</el-button>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%; margin: 20px 0"
        header-cell-class-name="table-header"
    >
      <el-table-column prop="username" label="用户名" min-width="120px" />
      <el-table-column prop="email" label="邮箱" min-width="200px" />
      <el-table-column prop="phoneNumber" label="手机号" min-width="120px" />
      <el-table-column prop="status" label="状态" min-width="100px">
        <template #default="{ row }">
          <el-tag
              :type="row.status === '0' ? 'success' : 'danger'"
              effect="dark"
              size="small"
          >
            {{ row.status === '0' ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180px">
        <template #default="{ row }">
          <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-switch
              v-model="row.status"
              :active-value="'0'"
              :inactive-value="'1'"
              @change="handleStatusChange(row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :loading="row.loading"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="编辑用户"
        width="30%"
        :before-close="handleClose"
    >
      <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="formData.phoneNumber" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button
              type="primary"
              @click="handleSubmit"
              :loading="submitLoading"
          >
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页控件 -->
    <el-pagination
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="fetchData"
        class="pagination"
    />
  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import adminApi from "@/apis/adminApi"

// 查询参数
const queryParams = ref({
  currentPage: 1,
  pageSize: 10,
  username: '',
  email: '',
  phoneNumber: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const formRef = ref(null)
const submitLoading = ref(false)
const formData = ref({
  id: null,
  username: '',
  email: '',
  phoneNumber: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 获取数据
const fetchData = async () => {
  const res = await adminApi.getAllData(queryParams.value)
  if (res.code === 200) {
    tableData.value = res.data.records
    total.value = res.data.total
  }
}

// 处理查询
const handleSearch = () => {
  queryParams.value.currentPage = 1
  fetchData()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.value.pageSize = size
  fetchData()
}

// 处理状态切换
const handleStatusChange = async (row) => {
  try {
    row.loading = true
    const res = await adminApi.changeStatus({
      id: row.id,
      status: row.status
    })
    if (res.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      throw new Error(res.message)
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
    row.status = row.status === '0' ? '1' : '0'
  } finally {
    row.loading = false
  }
}

// 处理编辑
const handleEdit = (row) => {
  formData.value = {
    id: row.id,
    username: row.username,
    email: row.email,
    phoneNumber: row.phoneNumber
  }
  dialogVisible.value = true
}

// 关闭对话框
const handleClose = () => {
  formRef.value.resetFields()
  dialogVisible.value = false
}

// 提交修改
const handleSubmit = async () => {
  try {
    submitLoading.value = true
    await formRef.value.validate()

    const res = await adminApi.updateById(formData.value)
    if (res.code === 200) {
      ElMessage.success('更新成功')
      fetchData()
      handleClose()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 初始化数据
fetchData()
</script>

<style scoped>
.full-card {
  margin: 20px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  border-radius: 4px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.search-form :deep(.el-form-item__content) {
  width: 100%;
}

.search-btn {
  margin-top: 20px;
  float: right;
}

.table-header {
  background: #f5f7fa !important;
  font-weight: 600;
}

.el-table {
  margin: 20px 0;
}

.pagination {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-switch) {
  transform: scale(0.9);
}
:deep(.el-dialog__body) {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
